--[[
Project: HunterRP
File: init.lua
Author: Sebihunter
]]--
require("datastream")

AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "cl_drawfuncs.lua" )
AddCSLuaFile( "cl_charcreate.lua" )
AddCSLuaFile( "cl_chat.lua" )
AddCSLuaFile( "shared.lua" )
AddCSLuaFile( "door_funcs.lua" )
AddCSLuaFile( "cl_scoreboard.lua" )
AddCSLuaFile( "cl_stamina.lua" )
 
 
include( 'shared.lua' )
include( 'door_funcs.lua' )
include( 'doors.lua' )
include( 'npcs.lua' )
include( 'chat.lua' )
include( 'admin.lua' )
include( 'commands.lua' )

--Defines
citizen_payday = 50
police_payday = 100
medic_payday = 90
mayor_payday = 100
economy = 1


function tables_exist() 
	if (sql.TableExists("player_info")) then
		Msg("Tables already exist, moving along!\n")
	else
		if (!sql.TableExists("player_info")) then
			query = "CREATE TABLE player_info ( unique_id varchar(255), money int, model varchar(255), firstname varchar(255), lastname varchar(255) )"
			result = sql.Query(query)
			if (sql.TableExists("player_info")) then
				Msg("Succes ! table 1 created \n")
			else
				Msg("Somthing went wrong with the player_info query ! \n")
				Msg( sql.LastError( result ) .. "\n" )
			end	
		end
	end
end

function player_exists ( ply )
	steamID = ply:GetNWString("SteamID")
	
	result = sql.Query("SELECT unique_id, money FROM player_info WHERE unique_id = '"..steamID.."'")
	if (result) then
			ply:SetNWInt("registered", 1)
			sql_value_stats( ply ) 
	else
		ply:SetNWInt("registered", 0)
		ply:ConCommand( "menu_charcreate" )
		--new_player( steamID, ply ) -- Create a new player :D
	end
	
end

function new_player( ply, command, args )
	if args == "" then return "" end
	if tonumber(ply:GetNWString("registered")) == 0 then
		steamID = ply:GetNWString("SteamID")
		sql.Query( "INSERT INTO player_info (`unique_id`, `money`, `model`, `firstname`, `lastname`) VALUES ('"..steamID.."', '500', '"..tostring(args[1]).."', 'Minge', 'Bag')" )
		result = sql.Query( "SELECT unique_id, money FROM player_info WHERE unique_id = '"..steamID.."'" )
		if (result) then
			Msg("Player account created !\n")
			ply:SetNWInt("registered", 1)
			sql_value_stats( ply )
		else
			Msg("Something went wrong with creating a players info !\n")
		end
	end
end
concommand.Add( "new_player", new_player ) 

function setCityEconomy( value )
	if 0.0 <= value and 2 >= value then
		datastream.StreamToClients( player.GetAll( ), "setClientCityEconomy", { ["economy"] = value } );
		economy = value
	end	
end

function showPlayerMessagebox( ply, title, string )
	datastream.StreamToClients( ply, "showPlayerMessagebox", { ["title"] = title, ["text"] = string } );
end

function showPlayerSelectionMessagebox( ply, title, string, button1, button2, callyes )
	datastream.StreamToClients( ply, "showPlayerSelectionMessagebox", { ["title"] = title, ["text"] = string, ["button1"] = button1, ["button2"] = button2, ["callfunc"] = callyes } );
end

function change_name( ply, command, args )
	if args == "" then return "" end
	if ply:GetNWString("firstname") == "Minge" and ply:GetNWString("lastname") == "Bag" then
		ply:SetNWString("firstname", args[1])
		ply:SetNWString("lastname", args[2])
		ply:SetNWString("name", args[1].." "..args[2])
		sql.Query("UPDATE player_info SET firstname = '"..args[1].."' WHERE unique_id = '"..unique_id.."'")
		sql.Query("UPDATE player_info SET lastname = '"..args[2].."' WHERE unique_id = '"..unique_id.."'")
		timer.Create("spawnUnfreeze", 1, 1, function() 
			ply:UnLock()
			ply:Freeze( false )
		end)	
	end
end
concommand.Add( "change_name", change_name ) 

function sql_value_stats ( ply )
	unique_id = sql.QueryValue("SELECT unique_id FROM player_info WHERE unique_id = '"..steamID.."'")
	money = sql.QueryValue("SELECT money FROM player_info WHERE unique_id = '"..steamID.."'")
	model = sql.QueryValue("SELECT model FROM player_info WHERE unique_id = '"..steamID.."'")
	firstname = sql.QueryValue("SELECT firstname FROM player_info WHERE unique_id = '"..steamID.."'")
	lastname = sql.QueryValue("SELECT lastname FROM player_info WHERE unique_id = '"..steamID.."'")
	ply:SetNWString("unique_id", unique_id)
	ply:SetNWInt("money", money)
	ply:SetNWString("model", model)
	ply:SetNWString("firstname", firstname)
	ply:SetNWString("lastname", lastname)
	ply:SetNWString("name", firstname.." "..lastname)
	ply:Spawn()
	if firstname == "Minge" or lastname == "Bag" then
		ply:ConCommand( "menu_name" )
	else
		timer.Create("spawnUnfreeze", 1, 1, function() 
			ply:UnLock()
			ply:Freeze( false )
		end)		
	end
end

function saveStat ( ply )
	if tonumber(ply:GetNWInt("registered")) == 1 then
		money = ply:GetNWInt("money")
		unique_id = ply:GetNWString ("SteamID")
		sql.Query("UPDATE player_info SET money = "..money.." WHERE unique_id = '"..unique_id.."'")
		--ply:ChatPrint("Stats sucessfully saved!")
	end
end


function Initialize()
	tables_exist()
	initDoors()
	initNPCs()
	
	timer.Create( "PayDay", 180, 0, function()
		for k, v in pairs(player.GetAll()) do
			if v:Team() == 1 then
				v:SetNWInt("money",((v:GetNWInt("money"))+citizen_payday*economy))
				v:PrintMessage(HUD_PRINTTALK, "You recieved "..tostring(citizen_payday*economy).."$ for beeing a citizen.")
			elseif	v:Team() == 2 then
				v:SetNWInt("money",((v:GetNWInt("money"))+police_payday*economy))
				v:PrintMessage(HUD_PRINTTALK, "You recieved "..tostring(police_payday*economy).."$ for beeing an officer.")			
			elseif	v:Team() == 3 then
				v:SetNWInt("money",((v:GetNWInt("money"))+medic_payday*economy))
				v:PrintMessage(HUD_PRINTTALK, "You recieved "..tostring(medic_payday*economy).."$ for beeing a medic.")	
			elseif	v:Team() == 4 then
				v:SetNWInt("money",((v:GetNWInt("money"))+mayor_payday*economy))
				v:PrintMessage(HUD_PRINTTALK, "You recieved "..tostring(mayor_payday*economy).."$ for beeing the mayor.")	
			end
		end
	end )
end
hook.Add( "Initialize", "Initialize", Initialize )

function GM:PlayerInitialSpawn( ply )
	timer.Create("Steam_id_delay", 1, 1, function()	
		SteamID = ply:SteamID()				
		ply:SetNWString("SteamID", SteamID)		
		timer.Create("SaveStat", 10, 0, function() saveStat( ply ) end)	 
		player_exists( ply )

		ply:SetTeam( 1 )
		ply:PrintMessage( HUD_PRINTTALK, "Welcome to HunterRP "..(ply:GetName()) )
		GAMEMODE:SetPlayerSpeed(ply, 100, 300)
		ply:Freeze( true )	
		ply:Lock()		
	end) 
end
hook.Add( "PlayerInitialSpawn", "PlayerInitialSpawn", PlayerInitialSpawn ) 
 
function GM:PlayerLoadout( ply ) 
	ply:Give( "weapon_physcannon" )
	ply:Give( "keys" )
	if ply:Team() == 1 then
		ply:SetModel(tostring(ply:GetNWString ("model")))
    elseif ply:Team() == 2 then
		ply:SetModel("models/player/combine_soldier.mdl")
		ply:Give( "weapon_pistol" )
		ply:Give( "weapon_stunstick" )	
	elseif ply:Team() == 3 then
		ply:SetModel("models/player/combine_super_soldier.mdl")	
    elseif ply:Team() == 4 then
		ply:SetModel("models/player/breen.mdl")
	end
end
hook.Add( "PlayerLoadout", "PlayerLoadout", PlayerLoadout ) 

function GM:PlayerSetModel( ply )
	if ply:Team() == 1 then
		ply:SetModel(tostring(ply:GetNWString ("model")))
    elseif ply:Team() == 2 then
		ply:SetModel("models/player/combine_soldier.mdl")
	elseif ply:Team() == 3 then
		ply:SetModel("models/player/combine_super_soldier.mdl")	
    elseif ply:Team() == 4 then
		ply:SetModel("models/player/breen.mdl")
	end
end

function PlayerDisconnect( ply )
	saveStat ( ply )
end
hook.Add( "PlayerDisconnected", "playerdisconnected", PlayerDisconnect )

	
function GM:AcceptStream( pl, handler, id )
 
    return true;
 
end
 
function setStaminaEffect( ply, handle, id, encoded, decoded )
	if decoded.iseffect == "1" then
		GAMEMODE:SetPlayerSpeed(ply, 100, 100)
	else
		GAMEMODE:SetPlayerSpeed(ply, 100, 300)
	end
end
datastream.Hook( "setStaminaEffect", setStaminaEffect );

function setPlayerCitizen( ply, handle, id, encoded, decoded )
	local pos = ply:GetPos()
	local ang = ply:GetAngles()
	ply:SetTeam( 1 ) 
	ply:Spawn()
	ply:SetPos(pos)
	ply:SetAngles(ang)
end
datastream.Hook( "setPlayerCitizen", setPlayerCitizen );

function setPlayerPolice( ply, handle, id, encoded, decoded )
	local pos = ply:GetPos()
	local ang = ply:GetAngles()
	ply:SetTeam( 2 ) 
	ply:Spawn()
	ply:SetPos(pos)
	ply:SetAngles(ang)
end
datastream.Hook( "setPlayerPolice", setPlayerPolice );

function setPlayerMedic( ply, handle, id, encoded, decoded )
	local pos = ply:GetPos()
	local ang = ply:GetAngles()
	ply:SetTeam( 3 ) 
	ply:Spawn()
	ply:SetPos(pos)
	ply:SetAngles(ang)
end
datastream.Hook( "setPlayerMedic", setPlayerMedic );

function GM:KeyPress ( Player, Key )
	if Key == IN_USE then
		local Tr = Player:GetEyeTrace();
		
		if Tr.Entity and Tr.Entity:IsValid() and Tr.Entity:GetClass() == "npc_eli" and Tr.Entity:GetPos():Distance(Player:GetPos()) < 100 then
			onNPCUse(Player, Tr.Entity)
		end
	end
end

function getPlayerInt()
	local players = 0
	for k, v in pairs(player.GetAll()) do
		players = players+1
	end
	return players
end

function getPlayerTeamInt(teamid)
	local players = 0
	for _,ply in pairs(team.GetPlayers(teamid)) do
		players = players+1
	end
	return players
end 
 